#!/usr/bin/python

'''
This script is used to get random N windows (with given size)
on the given genome (with given chromosomes)
'''

import re, os, sys, shutil
from optparse import OptionParser
from math import *
from random import *
from bisect import *

import GenomeData

def getRandomeWindow(infile, outfilename, species, window_size, number):
    outfile = open(outfilename, 'w');
    chroms = [];
    chromsfile = open(infile, 'r');
    for lines in chromsfile:
        lines = lines.strip().split();
        chroms.append(lines[0]);

    chrom_lengths = [];
    for c in chroms:
        chrom_lengths.append(GenomeData.species_chrom_lengths[species][c]);

    (genome_length, chrom_starts) = getGenomeLength(chrom_lengths);

    for i in range(number):
        rand_pos = randrange(genome_length);
        rand_chrom = getChrom(rand_pos, chrom_starts, chroms);
        length = GenomeData.species_chrom_lengths[species][rand_chrom];
        r_read_start = randrange(length);
        r_read_end = r_read_start + window_size - 1;
        outline = rand_chrom + "\t" + str(r_read_start) + "\t" +  str(r_read_end) + "\n";
        outfile.write(outline);
    outfile.close();


def getGenomeLength(chrom_lengths):
    genome = 0;
    chrom_starts = [];
    for l in chrom_lengths:
        genome += l;
        chrom_starts.append(genome);
    return (genome, chrom_starts);

def getChrom(pos, chrom_starts, chroms):
    start_ind = bisect_right(chrom_starts, pos);
    return chroms[start_ind];




def main(argv):
    parser = OptionParser()
    parser.add_option("-l", "--chromosomelist", action="store", type="string",
                      dest="list", help="file with a list of chromosome", metavar="<file>")
    parser.add_option("-o", "--outfile", action="store", type="string",
                      dest="outfile", help="the name of the output BED file", metavar="<file>")
    parser.add_option("-n", "--number", action="store", type="int",
                      dest="number", help="number of random windows, default: 100,000",
                      metavar="<int>", default=100000)
    parser.add_option("-s", "--species", action="store", type="string",
                      dest="species", help="species, default: hg19", metavar="<str>", default="hg19")
    parser.add_option("-w", "--windowsize", action="store", type="int",
                      dest="window", help="window size for scan genome, default: 250",
                      metavar="<int>", default=250)

    (opt, args) = parser.parse_args(argv)
    if len(argv) < 2:
        parser.print_help()
        sys.exit(1)

    getRandomeWindow(opt.list, opt.outfile, opt.species, opt.window, opt.number)

if __name__ == "__main__":
    main(sys.argv)


